package com.bnz.shop.controller;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.bnz.pojo.R;
import com.bnz.shop.config.OssProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@RestController
@RequestMapping("/shop")
public class uploadFileController {
    @Autowired
    private OssProperties ossProperties;
    //文件上传
    @PostMapping("/uploadFile")
    public R uploadFile(MultipartFile file){
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = ossProperties.getEndpoint();
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = ossProperties.getAccessKeyId();
        String accessKeySecret = ossProperties.getAccessKeySecret();
        // 填写Bucket名称，例如examplebucket。
        String bucketName = ossProperties.getBucketName();
        // 定义上传的文件名
        String fileName = "";
        System.out.println("endpoint = " + endpoint);
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            //1. 得到当前日期串
            String dtStr = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
            //2. 构造文件名
            fileName = dtStr + "/" + UUID.randomUUID().toString() + file.getOriginalFilename();
            System.out.println("fileName = " + fileName);
            //3. 得到当前文件的输入流对象
            InputStream inputStream = file.getInputStream();
            //4. 开始文件上传
            ossClient.putObject(bucketName,fileName,inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        //5. 构造上传后的url地址
        String url = "http://" + bucketName + "." + endpoint + "/" + fileName;
        return R.ok().put("url",url);
    }
}
